<template>
  <div class="password-form">
    <el-form
        ref="passwordFormRef"
        :model="passwordData"
        :rules="passwordRules"
        label-width="100px"
    >
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
            v-model="passwordData.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="passwordData.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
        />
        <div class="password-strength">
          <div class="strength-bar">
            <div
                class="strength-fill"
                :class="strengthClass"
                :style="{ width: strengthWidth }"
            ></div>
          </div>
          <span class="strength-text" :class="strengthClass">{{ strengthText }}</span>
        </div>
        <div class="password-tips">
          <p>密码要求：</p>
          <ul>
            <li :class="{ valid: hasMinLength }">至少8个字符</li>
            <li :class="{ valid: hasUpperCase }">包含大写字母</li>
            <li :class="{ valid: hasLowerCase }">包含小写字母</li>
            <li :class="{ valid: hasNumber }">包含数字</li>
            <li :class="{ valid: hasSpecialChar }">包含特殊字符</li>
          </ul>
        </div>
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="passwordData.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
        />
      </el-form-item>
    </el-form>

    <div class="security-tips">
      <el-alert
          title="安全提示"
          type="info"
          :closable="false"
      >
        <ul class="tips-list">
          <li>为了您的账户安全，请定期更换密码</li>
          <li>请不要使用简单或常见的密码</li>
          <li>请不要与他人分享您的密码</li>
          <li>修改密码后，需要重新登录</li>
        </ul>
      </el-alert>
    </div>

    <div class="form-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        修改密码
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const emit = defineEmits(['close'])

// 响应式数据
const submitLoading = ref(false)
const passwordFormRef = ref()

// 表单数据
const passwordData = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码强度检测
const hasMinLength = computed(() => passwordData.newPassword.length >= 8)
const hasUpperCase = computed(() => /[A-Z]/.test(passwordData.newPassword))
const hasLowerCase = computed(() => /[a-z]/.test(passwordData.newPassword))
const hasNumber = computed(() => /\d/.test(passwordData.newPassword))
const hasSpecialChar = computed(() => /[!@#$%^&*(),.?":{}|<>]/.test(passwordData.newPassword))

const passwordStrength = computed(() => {
  let score = 0
  if (hasMinLength.value) score++
  if (hasUpperCase.value) score++
  if (hasLowerCase.value) score++
  if (hasNumber.value) score++
  if (hasSpecialChar.value) score++
  return score
})

const strengthClass = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 2) return 'weak'
  if (strength <= 3) return 'medium'
  return 'strong'
})

const strengthWidth = computed(() => {
  return `${(passwordStrength.value / 5) * 100}%`
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 2) return '弱'
  if (strength <= 3) return '中'
  return '强'
})

// 自定义验证函数
const validateCurrentPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入当前密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'))
  } else {
    callback()
  }
}

const validateNewPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'))
  } else if (!hasMinLength.value) {
    callback(new Error('密码至少需要8个字符'))
  } else if (passwordStrength.value < 3) {
    callback(new Error('密码强度太弱，请包含大小写字母、数字和特殊字符'))
  } else if (value === passwordData.currentPassword) {
    callback(new Error('新密码不能与当前密码相同'))
  } else {
    // 重新验证确认密码
    if (passwordData.confirmPassword) {
      passwordFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordData.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const passwordRules = {
  currentPassword: [{ validator: validateCurrentPassword, trigger: 'blur' }],
  newPassword: [{ validator: validateNewPassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
}

// 方法
const handleSubmit = async () => {
  try {
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate()

    // 额外的安全检查
    if (passwordData.newPassword === passwordData.currentPassword) {
      ElMessage.error('新密码不能与当前密码相同')
      return
    }

    await ElMessageBox.confirm(
        '修改密码后需要重新登录，确定要继续吗？',
        '确认修改',
        {
          confirmButtonText: '确定修改',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    submitLoading.value = true

    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 模拟密码验证失败的情况（实际应用中由服务器返回）
    if (passwordData.currentPassword !== '123456') {
      ElMessage.error('当前密码不正确')
      return
    }

    ElMessage.success('密码修改成功，请重新登录')

    // 清空表单
    Object.assign(passwordData, {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    emit('close')

    // 实际应用中，这里应该跳转到登录页面
    setTimeout(() => {
      window.location.href = '/login'
    }, 1000)

  } catch (error) {
    if (error !== 'cancel') {
      console.error('密码修改失败:', error)
    }
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  // 清空表单
  Object.assign(passwordData, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })

  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }

  emit('close')
}
</script>

<style scoped>
.password-form {
  padding: 20px 0;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background-color: #e4e7ed;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s;
}

.strength-fill.weak {
  background-color: #f56c6c;
}

.strength-fill.medium {
  background-color: #e6a23c;
}

.strength-fill.strong {
  background-color: #67c23a;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
  min-width: 12px;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.medium {
  color: #e6a23c;
}

.strength-text.strong {
  color: #67c23a;
}

.password-tips {
  margin-top: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.password-tips p {
  margin: 0 0 8px 0;
  font-size: 13px;
  color: #333;
  font-weight: 500;
}

.password-tips ul {
  margin: 0;
  padding-left: 16px;
  list-style: none;
}

.password-tips li {
  font-size: 12px;
  color: #999;
  line-height: 1.6;
  position: relative;
}

.password-tips li::before {
  content: '○';
  position: absolute;
  left: -16px;
  color: #ddd;
}

.password-tips li.valid {
  color: #67c23a;
}

.password-tips li.valid::before {
  content: '●';
  color: #67c23a;
}

.security-tips {
  margin: 24px 0;
}

.tips-list {
  margin: 8px 0 0 0;
  padding-left: 20px;
  list-style: disc;
}

.tips-list li {
  font-size: 13px;
  line-height: 1.6;
  color: #666;
}

.form-footer {
  margin-top: 24px;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  padding-top: 16px;
}
</style>